package com.wlts.wzy.DYGoodsModule.DYapi;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wlts.wzy.api.request.dy.*;
import com.wlts.wzy.api.response.dy.*;
import com.wlts.wzy.util.StringUtils;
import com.wlts.wzy.util.http.HttpClient;
import io.reactivex.Single;
import lombok.SneakyThrows;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

public class DySdk {

    private static String baseUrl = "https://openapi-fxg.jinritemai.com";


    /**
     * 获得运费模板
     */
    @SneakyThrows
    public static DyFreightTemplateResponse getfreightTemplateList(String AppKey, String appSecret, String accesstoken, int page, int size, String name) {

        String Api = baseUrl + "/freightTemplate/list";

        String method = "freightTemplate.list";


        TreeMap<String, String> paramJson = new TreeMap<>();
//        paramJson.put("check_status",checkStatus);
        paramJson.put("page", page + "");
        paramJson.put("size", size + "");
        if (name != null) {
            paramJson.put("name", name);
        }

//        paramJson.put("status",status);
        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        DyFreightTemplateResponse response = new DyFreightTemplateResponse();

        JSONArray array = object.getJSONObject("data").getJSONArray("List");

        response.setJsonArray(array);

        //   System.err.println(response.toString());

        return response;

    }


    /**
     * 添加商品
     */
    @SneakyThrows
    public static AddGoodsToDyResponse DyAddV2(String AppKey, String appSecret, String accesstoken, AddGoodsToDyApiRequest request) {

        String Api = baseUrl + "/product/addV2";

        String method = "product.addV2";

        System.out.println("同步参数=====>"+request);
        TreeMap<String, String> paramJson = StringUtils.entityToTreeMap(request);
        System.out.println("同步参数=====>"+paramJson);

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);
        System.err.println(object);

        AddGoodsToDyResponse response = JSONObject.toJavaObject(object.getJSONObject("data"), AddGoodsToDyResponse.class);

//        System.err.println(response.toString());
        return response;

    }


    /**
     * 查看商品类目
     */
    @SneakyThrows
    public static List<GetShopCategoryDyResponse> getDyShopCategory(String AppKey, String appSecret, String accesstoken, GetShopCategoryDyRequest request) {

        String Api = baseUrl + "/shop/getShopCategory";

        String method = "shop.getShopCategory";


        TreeMap<String, String> paramJson = StringUtils.entityToTreeMap(request);

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        List<GetShopCategoryDyResponse> response = JSONArray.parseArray(object.getString("data"), GetShopCategoryDyResponse.class);

        //  System.err.println(response.toString());

        return response;

    }


    /**
     * 删除商品
     */
    @SneakyThrows
    public static boolean productDel(String AppKey, String appSecret, String accesstoken, DelGoodsToDyRequest request) {

        String Api = baseUrl + "/product/del";

        String method = "product.del";


        TreeMap<String, String> paramJson = StringUtils.entityToTreeMap(request);

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        System.err.println(object.toString());

        int errNo=object.getInteger("err_no");

        return errNo == 0;

    }


    /**
     * 抖音发货
     */
    @SneakyThrows
    public static List<UpdateDyOrdersResponse> orderList(String AppKey, String appSecret, String accesstoken, PageOrderToDyApiRequest request) {

        String Api = baseUrl + "/order/searchList";

        String method = "order.searchList";

        TreeMap<String, String> paramJson = StringUtils.entityToTreeMap(request);

        long st = Timestamp.valueOf(paramJson.get("start_time")).getTime() / 1000;
        long ed = Timestamp.valueOf(paramJson.get("end_time")).getTime() / 1000;

        paramJson.put("create_time_start", Long.toString(st));
        paramJson.put("create_time_end", Long.toString(ed));

        System.out.println(paramJson);

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        // System.out.println(object);

        JSONArray jsonArray = object.getJSONObject("data").getJSONArray("shop_order_list");

      //   System.out.println(object);

        if (jsonArray != null) {
            List<UpdateDyOrdersResponse> responseList = new ArrayList<>();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject item = jsonArray.getJSONObject(i);
                String shopId = item.getString("shop_id");
                JSONArray logisticsInfo = item.getJSONArray("logistics_info");
                String logisticsId = "0";
                String logisticsCode = "0";
                if (logisticsInfo.size() > 0) {
                    String company = logisticsInfo.getJSONObject(0).getString("company");
                    logisticsId = getLogisticsId(AppKey, appSecret, accesstoken, company);
                    logisticsCode = logisticsInfo.getJSONObject(0).getString("tracking_no");
                }
                JSONArray child = item.getJSONArray("sku_order_list");
                JSONArray newChild = new JSONArray();
                for(int j = 0; j < child.size(); j++) {
                    JSONObject childItem = child.getJSONObject(j);
                    String orderId = childItem.getString("order_id");
                    String cipherText = childItem.getString("encrypt_post_tel");
                    String postTel = decode(AppKey, appSecret, accesstoken, cipherText, orderId);
                    childItem.put("post_tel", postTel);
                    cipherText = childItem.getString("encrypt_post_receiver");
                    String postRec = decode(AppKey, appSecret, accesstoken, cipherText, orderId);
                    childItem.put("post_receiver", postRec);
                    JSONObject post_addr = childItem.getJSONObject("post_addr");
                    cipherText = post_addr.getString("encrypt_detail");
                    String detail = decode(AppKey, appSecret, accesstoken, cipherText, orderId);
                    post_addr.put("detail", detail);
                    childItem.put("post_addr", post_addr);
                    childItem.put("pid", childItem.getString("parent_order_id"));
                    childItem.put("final_status", childItem.getString("order_status"));
                    childItem.put("combo_num", childItem.getString("item_num"));
                    childItem.put("combo_amount", childItem.getString("origin_amount"));
                    childItem.put("spec_desc", childItem.getJSONArray("spec").toJSONString());
                    childItem.put("logistics_time", childItem.getString("ship_time"));
                    childItem.put("total_amount", childItem.getString("pay_amount"));
                    childItem.put("logistics_time", childItem.getString("ship_time"));
                    childItem.put("receipt_time", childItem.getString("logistics_receipt_time"));
                    childItem.put("shop_id", shopId);
                    childItem.put("logistics_id", logisticsId);
                    childItem.put("urge_cnt", "0");
                    if (!logisticsCode.equals("0")) {
                        childItem.put("logistics_code", logisticsCode);
                    }
                    Long payTime = childItem.getLong("pay_time");
                    if (payTime > 0) {
                        String payTimeFormat = sdf.format(payTime * 1000);
                        childItem.put("pay_time", payTimeFormat);
                    }
                    newChild.add(childItem);
                }
                List<UpdateDyOrdersResponse> array = JSONArray.parseArray(newChild.toJSONString(), UpdateDyOrdersResponse.class);
                responseList.addAll(array);
            }

         //   System.out.println(JSON.toJSONString(responseList));

            return responseList;
        } else {
            System.out.println(object);
        }


        return new ArrayList<>();

    }

    private static String decode(String AppKey, String appSecret, String accesstoken, String cipherText, String orderId) {
        String Api = baseUrl + "/order/batchDecrypt";

        String method = "order.batchDecrypt";

        TreeMap<String, List<Object>> paramJson = new TreeMap<>();

        JSONObject obj = new JSONObject();
        obj.put("auth_id", orderId);
        obj.put("cipher_text", cipherText);
        List<Object> list = new ArrayList<>();
        list.add(obj);
        paramJson.put("cipher_infos", list);

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        String decodeText = object.getJSONObject("data").getJSONArray("decrypt_infos").getJSONObject(0).getString("decrypt_text");

        return decodeText;
    }

    private static String getLogisticsId(String AppKey, String appSecret, String accesstoken, String searchCode) {
        String Api = baseUrl + "/order/logisticsCompanyList";
        String method = "order.logisticsCompanyList";
        TreeMap<String, List<Object>> paramJson = new TreeMap<>();

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        JSONArray list = object.getJSONArray("data");

        for (int i=0;i<list.size();i++){
            JSONObject item = list.getJSONObject(i);
            if (item.getString("code").equals(searchCode)) {
                return item.getString("id");
            }
        }

        System.out.println(list);

        return "0";
    }


    /**
     * 查询订单列表
     */
    @SneakyThrows
    public static LogisticsAddToDyApiResponse LogisticsAddSinglePack(String AppKey, String appSecret, String accesstoken, LogisticsAddToDyApiRequest request) {

        String Api = baseUrl + "/order/logisticsAddMultiPack";

        String method = "order.logisticsAddMultiPack";

        TreeMap<String, String> paramJson = StringUtils.entityToTreeMap(request);

        System.out.println(JSON.toJSONString(paramJson));


        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        LogisticsAddToDyApiResponse response = JSONObject.toJavaObject(object, LogisticsAddToDyApiResponse.class);

        return response;


    }

    /**
     * 查看快递代码
     */
    @SneakyThrows
    public static List<UpdateDyOrdersResponse> logisticsCompanyList(String AppKey, String appSecret, String accesstoken) {

        String Api = baseUrl + "/order/logisticsCompanyList";

        String method = "order.logisticsCompanyList";

        TreeMap<String, String> paramJson = new TreeMap<>();

        JSONObject object = DyApiClient.DYAoiGet(Api, method, AppKey, appSecret, accesstoken, paramJson);

        System.out.println(object);

        JSONArray jsonArray = object.getJSONObject("data").getJSONArray("list");


        return new ArrayList<>();

    }


    public static void main(String[] args) {

        String accessToken = "3fd12a57-74d5-4597-ac1f-598a08622c90";
        String appKey = "6920503223405200909";
        String appSecret = "3ea9bcf2-3f1c-425c-b369-588bf11405a2";

//        String access_token = "3fd12a57-74d5-4597-ac1f-598a08622c90";

        String refresh_token = "dd05f162-6894-45d6-a33f-597ed2d40d43";

        String shop_id = "11706735";

//        String appKey = "6920503223405200909";
//
//        String appSecret = "3ea9bcf2-3f1c-425c-b369-588bf11405a2";
//
//        getfreightTemplateList(appKey, appSecret, access_token, 0, 10, "123");

        //    .. 测试获取商品列表     https://openapi-fxg.jinritemai.com/product/list
        getfreightTemplateList(appKey, appSecret, accessToken, 0, 20, "");


    }


}





